import '../public/index'
import url from '../data/url'
import request from '../data/request'
import { header } from '../data/config'
import store from 'store'

const base                 = url.base,
      getRolePowerList     = request.getRolePowerList,
      modifyRolePermission = request.modifyRolePermission

// 页面标题
const title  = '角色权限',
      action =  '修改'

let form = new Vue({
  el: '#form',
  data: () => {
    return ({
      id        : '',
      power     : '',
      powerList : '',
      isLock    : false
    })
  },
  mounted: function() {

    let that = this
    
    let loading = layer.msg('初始化数据中...', {
      icon: 16,
      time: 0
    })

    let storeData = store.get('storeData')

    console.log(storeData)

    if (!storeData) {
      layer.msg('页面跳转错误', {
        icon: 5
      })

      setTimeout(() => {
        window.location = './index.html'
      }, 1000)

      return
    }

    Promise
      .all([this.getRolePowerList(storeData.idStr)])
      .then((res) => {

        layer.close(loading)

        that.isLock = false

        that.powerList = res[0].object
        that.id = storeData.idStr

        // setInterval(() => {
        //   console.log(that.formatData(that.powerList).join(','))
        // }, 1000)

        valid()
      })
      .catch((error) => {
        console.log(error)

        layer.close(loading)
        layer.msg(error || '初始化数据失败', {
          icon: 5
        })
      })
    
  },
  methods: {
    // 获取开发商列表
    getRolePowerList: (id) => (
      new Promise((resolve, reject) => {

            $.ajax({
              url: base + getRolePowerList,
              headers: header,
              data: {
                roleId: id
              }
            })
            .done(function(res) {
              if (res.code === 0) {
                resolve(res)
              }
              reject(res.message)
            })
            .fail(function() {
              console.log("error")
              reject()
            })
            .always(function() {
            })

          })

    ),
    // 序列化数据
    formatData: function(data) {
      
      let result = []

      formatData(data, [])

      function formatData(data, arr) {

        for (let i = 0, len = data.length; i < len; i++) {
          
          data[i].imark === 'true' && result.push(data[i].idStr)

          if (data[i].children instanceof Array) {
            formatData(data[i].children, arr)
          }

        }

      }
      
      return result

    },
    powerHandle: function(data, p) {

      p = (p instanceof Array) ? p : []

      if (data.imark === 'true') {
        // 关闭
        data.imark = ''

        // 关闭父节点
        if (p.length) {
          // 判断兄弟节点是否全部关闭
          let isCloseAll = true

          _.each(p[0].children, (item) => {
            if (item.imark === 'true') {
              isCloseAll = false
            }
          })
          
          // 如果兄弟全部关闭则父节点也关闭
          if (isCloseAll) {
            p[0].imark = ''
          }
        }

        // 关闭子节点
        if (data.children && data.children.length) {
          _.each(data.children, (item) => {
            item.imark = ''
          })
        }
        
      } else {
        // 打开
        data.imark = 'true'
        
        // 打开父节点
        if (p.length) {
          p[0].imark = 'true'
        }

        _.each(p, (item) => {
          item.imark = 'true'
        })
        
        // 儿子全部打开
        if (data.children && data.children.length) {
          _.each(data.children, (item) => {
            item.imark = 'true'
          })
        }

      }

    }
  }
})

function valid() {

  let form_valid,
      $form = $('#form')

  $.validator.setDefaults({ // 只能放在validate规则配置之前

    // 提交事件
    submitHandler: () => {
      console.log('submit!')

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      form.isLock = true

      $.ajax({
        url: base + modifyRolePermission,
        type: 'POST',
        headers: header,
        data: {
          id: form.id,
          functionIds: form.formatData(form.powerList).join(',')
        }
      })
        .done(function(res) {
          console.log(res)

          if (res.code === -1 ) {
            layer.msg(res.message, {
              icon: 5
            })

            return
          }

          layer.msg(`${ action }${ title }成功`, {
            icon: 6
          })

          // 重置表单
          $.extend(form.$data, form.$options.data())

          setTimeout(() => {
            window.location = './index.html'
          }, 1000)
        })
        .fail(function(res) {
          console.log(res)

          layer.msg(`${ action }${ title }失败`, {
            icon: 5
          })

          console.log("error");
        })
        .always(function(res) {

          layer.close(loading_modal)
          form.isLock = false

        })

    }
  })

  // 验证
  form_valid = $form.validate({
    errorPlacement:function(error, element) {
      error.appendTo(element.parents('.col-xs-24'))
    },
    rules: {}
  })

}